package com.bs.sc.front.user.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.bs.sc.base.utils.AjaxJson;
import com.bs.sc.front.user.entity.User;
import com.bs.sc.front.user.service.UserService;

@RestController
@RequestMapping(value = "/user")
@CrossOrigin
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 用户名判重
	 * 
	 * @param userName
	 * @return
	 */
	@RequestMapping(value = "findUserByUserName", method = RequestMethod.GET)
	public AjaxJson findUserByUserName(String userName) {
		AjaxJson j = new AjaxJson();
		List<User> users = userService.findUserByUserName(userName);
		if (users.size() > 0) {
			j.setCode("failure");
			j.setMsg("用户名重复");
		} else {
			j.setCode("success");
			j.setMsg("用户名可用");
		}
		return j;
	}

	/**
	 * 注册
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "register", method = RequestMethod.POST)
	public AjaxJson register(User user) {
		AjaxJson j = userService.register(user);
		return j;
	}

	/**
	 * 登录
	 * 
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public AjaxJson login(User user, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		List<User> users = userService.findUserByUserNameAndPassword(user.getUserName(), user.getPassword());
		if (users.size() > 0) {
			request.getSession().setAttribute("user", users.get(0));
			j.setCode("success");
			j.setMsg("登录成功");
		} else {
			j.setCode("failure");
			j.setMsg("用户名或密码不正确");
		}
		return j;
	}

	/**
	 * 获取登录用户session
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getSession", method = RequestMethod.POST)
	public AjaxJson getSession(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		User u = (User) request.getSession().getAttribute("user");
		System.out.println("session:" + u);
		if (u != null) {
			j.setCode("success");
			j.setMsg("获取session成功");
			j.setData(u);
		} else {
			j.setCode("failure");
			j.setMsg("session超时");
		}
		return j;
	}

	/**
	 * 退出登录
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public AjaxJson logout(HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		request.getSession().invalidate();
		j.setCode("success");
		j.setMsg("退出成功");
		return j;
	}

}
